package com.yeskery.nut.script.function.extend;

import com.yeskery.nut.core.NutException;
import com.yeskery.nut.script.function.Function;
import com.yeskery.nut.util.JsonUtils;
import com.yeskery.nut.util.StringUtils;

import javax.script.ScriptException;

/**
 * JS函数
 * @author sprout
 * @version 1.0
 * 2022-05-22 23:44
 */
public class JsFunction implements Function {
    @Override
    public String getName() {
        return "js";
    }

    @Override
    public String apply(String content) throws Exception {
        if (StringUtils.isEmpty(content)) {
            return content;
        }
        try {
            Object result = JsonUtils.engineFactory().eval(content);
            return result == null ? "" : result.toString();
        } catch (ScriptException e) {
            throw new NutException("JS Script Parse Fail.", e);
        }
    }
}
